package com.toolmanrln.logistics.modules.system.controller;


//import com.google.code.kaptcha.Producer;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.google.code.kaptcha.Producer;
import com.toolmanrln.common.api.ResponseData;
import com.toolmanrln.common.api.dto.TokenDTO;
import com.toolmanrln.common.base.BaseController;
import com.toolmanrln.logistics.modules.user.entity.User;
import com.toolmanrln.logistics.modules.user.service.IUserService;
import com.toolmanrln.security.component.VerifyCodeAuthenticationProvider;
import com.toolmanrln.security.util.JwtTokenUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.time.LocalDateTime;

/**
 * <p>
 * 用户信息表 前端控制器
 * </p>
 *
 * @author ToolMan.RLN
 * @since 2020-05-19
 */
@RestController
@RequestMapping
@Api(value = "系统操作服务API", tags = "系统操作服务API")
@Slf4j
public class SystemController extends BaseController {

    @Autowired
    private IUserService userService;

    @Autowired
    private Producer producer;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    @Value("${jwt.expiration}")
    private Long expiration;

    @ApiOperation(value = "用户注册", notes = "用户注册")
    @PostMapping(value = "/register")
    public ResponseData register(@ApiParam(name = "account", value = "账号", required = true) @RequestParam("account") String account,
                                 @ApiParam(name = "password", value = "密码(长度6到16位)", required = true) @RequestParam("password") String password,
                                 @ApiParam(name = VerifyCodeAuthenticationProvider.VERIFY_CODE, value = "验证码", required = true) @RequestParam(VerifyCodeAuthenticationProvider.VERIFY_CODE) String verifyCode, HttpServletRequest request) {
        User user = userService.register(account, password, request);
        Assert.notNull(user, "注册失败，请重新再试。");
        return ResponseData.success(user);
    }

    @ApiOperation(value = "用户登陆", notes = "用户登陆")
    @PostMapping(value = "/login")
    public ResponseData login(@ApiParam(name = "account", value = "账号", required = true) @RequestParam("account") String account,
                              @ApiParam(name = "password", value = "密码", required = true) @RequestParam("password") String password,
                              @ApiParam(name = VerifyCodeAuthenticationProvider.VERIFY_CODE, value = "验证码", required = true) @RequestParam(VerifyCodeAuthenticationProvider.VERIFY_CODE) String verifyCode, HttpServletRequest request) {
        return ResponseData.success(userService.login(account, password, request));
    }

    @ApiOperation(value = "用户登出", notes = "用户登出")
    @PostMapping(value = "/logout")
    public ResponseData login() {
        return ResponseData.success();
    }


    @ApiOperation(value = "获取验证码图片", notes = "用户登出")
    @GetMapping(value = "/verifyCode.jpg")
    public void verifyCode(@ApiIgnore HttpSession session, @ApiIgnore HttpServletResponse response) {
        response.setContentType("image/jpeg");
        String text = producer.createText();
        session.setAttribute(VerifyCodeAuthenticationProvider.VERIFY_CODE, text);
        BufferedImage image = producer.createImage(text);
        try (ServletOutputStream out = response.getOutputStream()) {
            ImageIO.write(image, "jpg", out);
        } catch (IOException e) {
            log.warn("获取验证码发生异常，报错信息：{}", e.getMessage());
        }
    }


    @ApiOperation(value = "刷新token", notes = "刷新token")
    @PostMapping(value = "/refreshToken")
    public ResponseData refreshToken(HttpServletRequest request) {
        String token = jwtTokenUtil.refreshHeadToken(request.getHeader(this.tokenHeader));
        return ResponseData.success(new TokenDTO(token, LocalDateTime.now().plusSeconds(expiration)));
    }


    @ApiOperation(value = "test", notes = "test")
    @PostMapping(value = "/test")
    public ResponseData test() {
        return ResponseData.success("测试成功");
    }
}

